package com.serverlite.system.main.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.serverlite.framework.dao.core.Dao;
import com.serverlite.framework.dao.core.Page;
import com.serverlite.framework.servlet.mapping.Controller;
import com.serverlite.framework.servlet.mapping.RequestMapping;
import com.serverlite.framework.utils.JsonUtils;
import com.serverlite.framework.utils.PropertiesUtils;
import com.serverlite.framework.utils.StringUtils;

/**
 * 数据常用操作接口
 * @author Neo
 *
 */
@Controller(value="/system/common")
public class CommonController {
    
    /**
     * 更新数据的方法(基本)
     * sql:更新的脚本
     * params:脚本参数(可变)
     */
    @RequestMapping(value="/update")
    public boolean update(HttpServletRequest request){
        try{
            String sql = request.getParameter("sql");
            String params = request.getParameter("params");
            Dao.update(sql, JsonUtils.json2Array(new JSONArray(params)));
            return true;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }
    
   /**
    * 查询数据的方法(基本),返回json数组
    * sql:更新的脚本
    * params:脚本参数(可变)
    */
    @RequestMapping(value="/query")
    public JSONArray query(HttpServletRequest request){
        try {
            String sql = request.getParameter("sql");
            String params = request.getParameter("params");
            Object[] p = JsonUtils.json2Array(new JSONArray(params));
            if(p!=null && p.length>0){
                return Dao.select(sql, p);
            } else {
                return Dao.select(sql);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 批量数据更新操作(基本)
     * sql:更新的脚本
     * params:脚本参数(可变)
     */
    @RequestMapping(value="/batch")
    public boolean batch(HttpServletRequest request){
        try{
            String sql = request.getParameter("sql");
            String p = request.getParameter("params");
            JSONArray array = new JSONArray(p);
            Object[][] params = JsonUtils.json2Arrays(array);
            Dao.batch(sql, params);
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 调用存储过程(基本)
     * procName:存储过程名称
     * params:输入参数(可变)
     */
    @RequestMapping(value="/callproc")
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public JSONArray callproc(HttpServletRequest request){
        try{
            String procName = request.getParameter("procName");
            String params = request.getParameter("params");
            Object[] p = JsonUtils.json2Array(new JSONArray(params));
            if(p!=null && p.length>0){
                List<Object> list = (List)Dao.callProc(procName, p);
                return JsonUtils.listv2json(list);
            } else {
                List<Object> list = (List)Dao.callProc(procName);
                return JsonUtils.listv2json(list);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 保存一个对象
     * table:表名
     * vo:值对象，数据格式为{"field1":"value1","field2":"value2",...}
     */
    @RequestMapping(value="/saveorupdate")
    public boolean saveorupdate(HttpServletRequest request){
        try{
            String table = request.getParameter("table");
            String vo = request.getParameter("vo");
            JSONObject o = new JSONObject(vo);
            Dao.saveOrUpdate(table, o);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 批量删除数据
     * 请求参数
     * table:表名
     * ids:要删除数据的id集合，以","隔开的字符串
     */
    @RequestMapping(value="/delete")
    public boolean delete(HttpServletRequest request){
        try{
            String table = request.getParameter("table");
            String ids = request.getParameter("ids");
            Dao.batchDeleteByIds(table, ids);
            return true;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 获取分页列表
     * 参数
     * table:表名
     * sortField:排序字段
     * sortOrder:排序方式(asc,desc)
     * pageSize:每页大小
     * pageIndex:当前页
     * where:查询条件
     */
    @RequestMapping(value="/list")
    public JSONObject list(HttpServletRequest request){
        String table = request.getParameter("table");
        String sortField = request.getParameter("sortField");
        String sortOrder = request.getParameter("sortOrder");
        String pageSize = request.getParameter("pageSize");
        String pageIndex = request.getParameter("pageIndex");
        String where = request.getParameter("where");
        JSONObject pageModel = new JSONObject();
        Page<Map<String,Object>> page = Dao.selectPage(table, where, sortField, sortOrder, Integer.valueOf(pageIndex), Integer.valueOf(pageSize));
        try {
            pageModel.put("pageIndex", page.getPageIndex());
            pageModel.put("pageSize", page.getPageSize());
            pageModel.put("pageTotal", page.getPageTotal());
            pageModel.put("total", page.getTotalCount());
            pageModel.put("data", page.getData());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return pageModel;
    }
    
    /**
     * 获取分页列表
     * 参数
     * sortField:排序字段
     * sortOrder:排序方式(asc,desc)
     * pageSize:每页大小
     * pageIndex:当前页
     * sql:查询脚本
     */
    @RequestMapping(value="/grid")
    public JSONObject grid(HttpServletRequest request){
        String sortField = request.getParameter("sortField");
        String sortOrder = request.getParameter("sortOrder");
        String pageSize = request.getParameter("pageSize");
        String pageIndex = request.getParameter("pageIndex");
        String sql = request.getParameter("sql");
        JSONObject pageModel = new JSONObject();
        Page<Map<String,Object>> page = Dao.selectPage(sql, sortField, sortOrder, Integer.valueOf(pageIndex), Integer.valueOf(pageSize));
        try {
            pageModel.put("pageIndex", page.getPageIndex());
            pageModel.put("pageSize", page.getPageSize());
            pageModel.put("pageTotal", page.getPageTotal());
            pageModel.put("total", page.getTotalCount());
            pageModel.put("data", page.getData());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return pageModel;
    }
    
    /**
     * 获取单表所有数据
     * 参数
     * table:表名
     */
    @RequestMapping(value="/all")
    public JSONArray all(HttpServletRequest request){
        String table = request.getParameter("table");
        return Dao.selectAll(table);
    }
    
    /**
     * 获取数据集合
     * 参数
     * sql:查询脚本
     */
    @RequestMapping(value="/many")
    public JSONArray many(HttpServletRequest request){
        String sql = request.getParameter("sql");
        return Dao.select(sql);
    }
    
    /**
     *根据ID获取对象
     *参数
     *table:表名
     *id:标识列
     *返回值 
     *返回这行数据的json对象
     */
    @RequestMapping(value="/get")
    public JSONObject get(HttpServletRequest request){
        JSONObject obj = null;
        String table = request.getParameter("table");
        String id = request.getParameter("id");
        Map<String,Object> map = null;
        if(!StringUtils.isEmpty(id)){
            map = Dao.selectById(table, id);
            obj = JsonUtils.map2json(map);
        }
        return obj;
    }
    
    
    /**
     * 保存数据到Session中
     * 参数
     * key:session key
     * vo:数据对象
     */
    @RequestMapping(value="/setsession")
    public boolean setsession(HttpServletRequest request){
        try{
            String key = request.getParameter("key");
            String vo = request.getParameter("vo");
            request.getSession().setAttribute(key, vo);
            return true;
        } catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 从Session中取出对象
     * 参数
     * key:session key
     */
    @RequestMapping(value="/getsession")
    public JSONObject getsession(HttpServletRequest request){
        String key = request.getParameter("key");
        String vo = (String) request.getSession().getAttribute(key);
        try {
            return new JSONObject(vo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 上传文件
     * @param request
     * @param response
     * @return
     * @throws JSONException
     */
    @RequestMapping(value="/upload")
    public JSONObject upload(HttpServletRequest request, HttpServletResponse response) throws JSONException{
        JSONObject result = new JSONObject();
        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if(isMultipart){
                String basePath = PropertiesUtils.get("sys.basePath");
                String uploadPath = PropertiesUtils.get("sys.uploadPath");
                String folderName = request.getParameter("folder");
                String rootPath = basePath + File.separator + uploadPath;
                if(!StringUtils.isEmpty(folderName)){
                    rootPath += File.separator + folderName;
                }
                File folder = new File(rootPath);
                if(!folder.exists()){
                    folder.mkdirs();
                }
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(request);
                Iterator<FileItem> itr = items.iterator();
                while(itr.hasNext()){
                    FileItem item = (FileItem) itr.next();
                    if(!item.isFormField()){
                        String fileName = item.getName();
                        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                        String path = rootPath + File.separator + newFileName;
                        path = path.replace("\\", "/");
                        File file = new File(path);
                        item.write(file);
                        result.put("name", fileName);
                        result.put("url", path.replace(basePath, ""));
                        result.put("status", "1");
                        result.put("message", "上传成功！");
                    }
                }
            }
        } catch(Exception e){
            e.printStackTrace();
            result.put("status", "0");
            result.put("message", "上传失败！");
        }
        return result;
    }
}
